package com.xunyin.modules.opengift.rest;


import com.xunyin.api.XunyinException;
import com.xunyin.constant.Constants;
import com.xunyin.enums.StatusEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.mtopengift.domain.MtOpenGift;
import com.xunyin.modules.mtopengift.service.OpenGiftService;
import com.xunyin.modules.mtopengift.service.dto.OpenGiftDto;
import com.xunyin.modules.mtusergrade.domain.MtUserGrade;
import com.xunyin.modules.mtusergrade.service.mapper.MtUserGradeMapper;
import com.xunyin.utils.SecurityUtils;
import com.xunyin.utils.StringUtil;
import com.xunyin.web.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开卡赠礼管理controller
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Slf4j
@Api(tags="管理端-开卡赠礼相关接口")
@RestController
@AllArgsConstructor
@RequestMapping(value = "api/openGift")

public class BackendOpenGiftController {

    /**
     * 会员服务接口
     */
    //private MemberService memberService;

    private final MtUserGradeMapper mtUserGradeMapper;

    /**
     * 开卡赠礼服务接口
     */
    private final OpenGiftService openGiftService;

    /**
     * 卡券服务接口
     */
    private final CouponService couponService;

    /**
     * 开卡赠礼列表查询
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @ApiOperation(value = "开卡赠礼列表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    //@PreAuthorize("@pms.hasPermission('openGift:index')")
    public ResponseEntity<Map<String, Object>> list(HttpServletRequest request) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String couponId = request.getParameter("couponId");
        String gradeId = request.getParameter("gradeId");
        String status = request.getParameter("status");
        Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));

        Map<String, Object> param = new HashMap<>();
/*        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            param.put("merchantId", accountInfo.getMerchantId());
        }*/
        if (StringUtil.isNotEmpty(couponId)) {
            param.put("couponId", couponId);
        }
        if (StringUtil.isNotEmpty(gradeId)) {
            param.put("gradeId", gradeId);
        }
        if (StringUtil.isNotEmpty(status)) {
            param.put("status", status);
        }
        //if (storeId > 0) {
            param.put("storeId", storeId);
        //}
        param.put("pageNumber", page);
        param.put("pageSize", pageSize);

        ResponseObject response = openGiftService.getOpenGiftList(param);

        Map<String, Object> params = new HashMap<>();
/*        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            params.put("MERCHANT_ID", accountInfo.getMerchantId());
        }*/

        List<MtUserGrade> userGradeList = mtUserGradeMapper.selectByMap(params);
        MtCoupon coupon = new MtCoupon();
        coupon.setStoreIds(String.valueOf(storeId));
        List<MtCoupon> mtCouponList = couponService.queryCouponListByCondi(coupon);
        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", response.getData());
        result.put("userGradeList", userGradeList);
        result.put("mtCouponList", mtCouponList);

        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 开卡赠礼详情
     * @param request HttpServletRequest对象
     * @return
     * */
    @ApiOperation(value = "开卡赠礼详情")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    //@PreAuthorize("@pms.hasPermission('openGift:index')")
    public ResponseEntity<Map<String, Object>> info(HttpServletRequest request, @PathVariable("id") Integer id) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        Map<String, Object> param = new HashMap<>();
/*        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            param.put("MERCHANT_ID", accountInfo.getMerchantId());
        }*/
        //List<MtUserGrade> userGradeMap = memberService.queryMemberGradeByParams(param);
        List<MtUserGrade> userGradeMap = mtUserGradeMapper.selectByMap(param);
        OpenGiftDto openGiftInfo = openGiftService.getOpenGiftDetail(id);
        Map<String, Object> result = new HashMap<>();
        result.put("openGiftInfo", openGiftInfo);
        result.put("userGradeMap", userGradeMap);

        return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 提交开卡赠礼
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @ApiOperation(value = "提交开卡赠礼")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    //@PreAuthorize("@pms.hasPermission('openGift:add')")
    public ResponseEntity handleSave(HttpServletRequest request, @RequestBody Map<String, Object> param) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        String id = param.get("id").toString();
        String gradeId = param.get("gradeId").toString();
        String couponId = param.get("couponId").toString();
        String couponNum = param.get("couponNum").toString();
        String point = param.get("point").toString();
        String storeId = param.get("storeId").toString();
        String status = param.get("status") == null ? StatusEnum.ENABLED.getKey() : param.get("status").toString();
        //Integer storeId = (param.get("storeId") == null || StringUtil.isEmpty(param.get("storeId").toString())) ? 0 : Integer.parseInt(param.get("storeId").toString());
        if (StringUtil.isEmpty(couponId) && StringUtil.isEmpty(couponNum) && StringUtil.isEmpty(point)) {
            //return getFailureResult(201, "积分和卡券必须填写一项");
            throw new XunyinException("积分和卡券必须填写一项");
        }

        if (StringUtil.isEmpty(gradeId)) {
            //return getFailureResult(201, "会员等级不能为空");
            throw new XunyinException("会员等级不能为空");
        }

        MtOpenGift reqDto = new MtOpenGift();
        if (StringUtil.isNotEmpty(couponId)) {
            reqDto.setCouponId(Integer.parseInt(couponId));
        } else {
            reqDto.setCouponId(0);
        }
        if (StringUtil.isNotEmpty(couponNum)) {
            reqDto.setCouponNum(Integer.parseInt(couponNum));
        } else {
            reqDto.setCouponNum(0);
        }
        if (StringUtil.isNotEmpty(gradeId)) {
            reqDto.setGradeId(Integer.parseInt(gradeId));
        } else {
            reqDto.setGradeId(0);
        }
        if (StringUtil.isNotEmpty(point)) {
            reqDto.setPoint(Integer.parseInt(point));
        } else {
            reqDto.setPoint(0);
        }
        reqDto.setMerchantId(0);
        reqDto.setStoreId(Integer.valueOf(storeId));
        reqDto.setStatus(status);
        String operator = SecurityUtils.getUsername();
        reqDto.setOperator(operator);

        if (StringUtil.isNotEmpty(id)) {
            reqDto.setId(Integer.parseInt(id));
            openGiftService.updateOpenGift(reqDto);
        } else {
            openGiftService.addOpenGift(reqDto);
        }

        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 更新开卡赠礼
     *
     * @return
     */
    @ApiOperation(value = "更新开卡赠礼")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @CrossOrigin
    //@PreAuthorize("@pms.hasPermission('openGift:index')")
    public ResponseEntity updateStatus(@RequestBody Map<String, Object> param) {
        Integer id = param.get("id") == null ? 0 : Integer.parseInt(param.get("id").toString());
        String status = param.get("status") == null ? StatusEnum.ENABLED.getKey() : param.get("status").toString();

        OpenGiftDto info = openGiftService.getOpenGiftDetail(id);
        if (info == null) {
            //return getFailureResult(201, "会员等级不存在");
            throw new XunyinException("会员等级不存在");
        }

        MtOpenGift reqDto = new MtOpenGift();
        reqDto.setId(id);
        reqDto.setStatus(status);

        openGiftService.updateOpenGift(reqDto);
        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }

    /**
     * 删除开卡赠礼
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "删除开卡赠礼")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @CrossOrigin
    //@PreAuthorize("@pms.hasPermission('openGift:index')")
    public ResponseEntity delete(HttpServletRequest request, @PathVariable("id") Integer id) {
/*        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }*/

        String operator = SecurityUtils.getUsername();
        openGiftService.deleteOpenGift(id, operator);
        return new ResponseEntity(HttpStatus.OK);
        //return getSuccessResult(true);
    }
}
